#include "EventLoopThread.h"
#include "EventLoop.h"

EventLoopThread::EventLoopThread(const ThreadInitCallback &cb,
            const std::string& name)
            : loop_(nullptr)
            , exiting_(false)
            , thread_(std::bind(&EventLoopThread::threadFunc, this), name) 
            , mutex_()
            , cond_()
            , callback_(cb)
{
}

EventLoopThread::~EventLoopThread() {
    exiting_ = true;
    if (loop_ != nullptr) {
        loop_->quit();
        thread_.join();
    }
}

EventLoop* EventLoopThread::startLoop() {
    thread_.start(); // 启动线程

    EventLoop *loop = nullptr;

    {
        std::unique_lock<std::mutex> lock(mutex_);
        while (loop_ == nullptr)
        {
            cond_.wait(lock); // 如果loop_已经构造好了就唤醒
        }
        loop = loop_; 
    }

    return loop;
}


// 在新线程中运行的函数
void EventLoopThread::threadFunc() {
    EventLoop loop; // 创建一个独立的loop 对应上面创建的线程， this is one loop per thread

    if (callback_) { // 如果构造函数传入了callback
        callback_(&loop);
    }
    {
        std::unique_lock<std::mutex> lock(mutex_);
        loop_ = &loop;
        cond_.notify_one();
    }
    loop.loop(); // 开启poller.epoll
    // 退出loop
    std::unique_lock<std::mutex> lock(mutex_);
    loop_ = nullptr;
}